package com.cinema.servlet.user;

import com.cinema.dao.UserDAO;
import com.cinema.entity.User;

import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 用户个人信息Servlet
 */
public class UserProfileServlet extends HttpServlet {
    private UserDAO userDAO = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        try {
            // 重新从数据库获取最新的用户信息
            User latestUser = userDAO.findById(user.getId());
            if (latestUser != null) {
                request.setAttribute("user", latestUser);
                // 更新session中的用户信息
                session.setAttribute("user", latestUser);
            } else {
                request.setAttribute("user", user);
            }

            // 检查是否有消息
            String message = request.getParameter("message");
            if (message != null && !message.trim().isEmpty()) {
                request.setAttribute("message", message);
            }

            String error = request.getParameter("error");
            if (error != null && !error.trim().isEmpty()) {
                request.setAttribute("error", error);
            }

            request.getRequestDispatcher("/user-profile.jsp").forward(request, response);

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "获取用户信息失败");
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");

        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/login");
            return;
        }

        String action = request.getParameter("action");

        if ("update".equals(action)) {
            handleUpdateProfile(request, response, currentUser);
        } else {
            doGet(request, response);
        }
    }

    /**
     * 处理更新个人信息
     */
    private void handleUpdateProfile(HttpServletRequest request, HttpServletResponse response, User currentUser)
            throws ServletException, IOException {

        String email = request.getParameter("email");
        String realName = request.getParameter("realName");
        String gender = request.getParameter("gender");
        String birthDateStr = request.getParameter("birthDate");

        try {
            // 验证输入
            String validationError = validateInput(email, realName);
            if (validationError != null) {
                response.sendRedirect(request.getContextPath() + "/user/profile?error=" +
                    URLEncoder.encode(validationError, "UTF-8"));
                return;
            }

            // 创建更新的用户对象
            User updateUser = new User();
            updateUser.setId(currentUser.getId());
            updateUser.setEmail(email);
            updateUser.setRealName(realName);
            updateUser.setGender(gender);

            // 处理生日
            if (birthDateStr != null && !birthDateStr.trim().isEmpty()) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date birthDate = sdf.parse(birthDateStr);
                    updateUser.setBirthDate(birthDate);
                } catch (ParseException e) {
                    response.sendRedirect(request.getContextPath() + "/user/profile?error=" +
                        URLEncoder.encode("生日格式不正确", "UTF-8"));
                    return;
                }
            }

            // 更新用户信息
            boolean success = userDAO.updateUser(updateUser);

            if (success) {
                // 更新session中的用户信息
                User updatedUser = userDAO.findById(currentUser.getId());
                if (updatedUser != null) {
                    request.getSession().setAttribute("user", updatedUser);
                }

                response.sendRedirect(request.getContextPath() + "/user/profile?message=" +
                    URLEncoder.encode("个人信息更新成功", "UTF-8"));
            } else {
                response.sendRedirect(request.getContextPath() + "/user/profile?error=" +
                    URLEncoder.encode("更新失败，请稍后重试", "UTF-8"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect(request.getContextPath() + "/user/profile?error=" +
                URLEncoder.encode("更新过程中发生错误", "UTF-8"));
        }
    }

    /**
     * 验证输入参数
     */
    private String validateInput(String email, String realName) {
        if (email != null && !email.trim().isEmpty()) {
            if (!isValidEmail(email)) {
                return "邮箱格式不正确";
            }
        }

        if (realName != null && !realName.trim().isEmpty()) {
            if (realName.trim().length() < 2 || realName.trim().length() > 20) {
                return "真实姓名长度应在2-20个字符之间";
            }
        }

        return null;
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        return email.matches(emailRegex);
    }
}
